package familytree.yu.com.sso.config;

import familytree.yu.com.adminclient.api.MemberInfoClientApiService;
import familytree.yu.com.adminclient.entity.MemberEntity;
import familytree.yu.com.sso.constants.Constants;
import familytree.yu.com.sso.model.LoginModel;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: yuyunbo
 * @Date: 2021/2/22 22:02
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @DubboReference
    private MemberInfoClientApiService memberInfoClientApiService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        MemberEntity user = memberInfoClientApiService.queryByUserName(username);
        if (user == null) {
            user = new MemberEntity();
            user.setMemberPhone(username);
            user.setMemberPassword(bCryptPasswordEncoder.encode(Constants.INITPASSWORD));
            memberInfoClientApiService.saveMemberInfo(user);
        }
        return new LoginModel(user, null);
    }
}
